<template>
    <div class="org">
        <el-row style="height: 100%">
            <el-col :span="7" style="padding: 10px 20px">
                <el-button-group>
                    <el-button type="primary" icon="el-icon-edit" @click="addOrg">新增小区</el-button>
                </el-button-group>
                <el-divider>小区列表</el-divider>
                <el-tree :data="treeData" :props="defaultProps" @node-click="handleNodeClick" :render-content="renderContent"></el-tree>
            </el-col>

            <el-col :span="17" style="height: 100%; border-left: 1px solid #e0e0e0; padding:5px 20px">
                <div>
                    <div style="width:100%;height:300px;position:relative;margin-bottom:10px">
                        <org-map :disabled="disabled" @map-serach="doPosition" style="position: absolute;top: 0;right: 10px;z-index: 1;"></org-map>
                        <div id="container" style="width:100%;height:100%"></div>
                    </div>
                    <el-form :model="submitForm" :rules="rules" label-width="100px" ref="submitForm">
                        <el-form-item label="父级ID" prop="parentId" v-show="false">
                            <el-input v-model="submitForm.parentId" :disabled="disabled"></el-input>
                        </el-form-item>
                        <el-form-item label="小区名称" prop="orgName">
                            <el-input v-model="submitForm.orgName" :disabled="disabled"></el-input>
                        </el-form-item>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="省/市/区(县)" prop="codes">
                                    <el-cascader :disabled="disabled" :options="options" v-model="submitForm.codes" @change="handleChange"></el-cascader>
                                    <!-- <el-input v-model="submitForm.orgProvince" :disabled="disabled"></el-input> -->
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="详细地址" prop="orgAddress">
                                    <el-input v-model="submitForm.orgAddress" :disabled="disabled"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <!-- <el-form-item label="市" prop="orgCity">
                            <el-input v-model="submitForm.orgCity" :disabled="disabled"></el-input>
                        </el-form-item>
                        <el-form-item label="区/县" prop="orgCounty">
                            <el-input v-model="submitForm.orgCounty" :disabled="disabled"></el-input>
                        </el-form-item>-->

                        <el-form-item label="机构LOGO" prop="orglogo">
                            <el-upload class="upload-demo" action="/xds/file/photo-upload" :data="fileData" :on-success="uploadSuccess" :limit="1">
                                <el-button type="text" size="small">上传文件</el-button>
                            </el-upload>
                        </el-form-item>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="经度" prop="longitude">
                                    <el-input-number v-model="submitForm.longitude" controls-position="right" :disabled="disabled"></el-input-number>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="纬度" prop="latitude">
                                    <el-input-number v-model="submitForm.latitude" controls-position="right" :disabled="disabled"></el-input-number>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="submitForm.remark" :disabled="disabled"></el-input>
                        </el-form-item>
                        <el-form-item label="排序" prop="sort">
                            <el-input-number v-model="submitForm.sort" :min="0" :max="1000" :disabled="disabled"></el-input-number>
                        </el-form-item>
                    </el-form>
                </div>
                <div style="text-align: right">
                    <el-button type="primary" icon="el-icon-edit" @click="doSave" :disabled="disabled">保 存</el-button>
                </div>
            </el-col>
        </el-row>
    </div>
</template>


<script>
//组织机构管理
import * as API from '@/api/admin/org'
import * as API2 from '@/api/business/car-owner'
import { regionData } from 'element-china-area-data'
import provinceAndCity from '@/util/province.json'
export default {
    data() {
        return {
            showAddBtn: false,
            showUpdateBtn: false,
            disabled: true,
            filePath: null,
            treeData: [],
            options: regionData,
            map: null,
            defaultProps: {
                children: 'children',
                label: 'name'
            },
            fileData: {
                filePrefix: 'logo'
            },
            submitForm: {
                orgName: '',
                sort: '',
                orgId: '',
                parentId: 0,
                latitude: '',
                longitude: '',
                orgLogo: '',
                orgAddress: '',
                remark: '',
                orgProvince: '',
                orgCity: '',
                orgCounty: '',
                delFlag: 0,
                codes: ''
            },
            rules: {
                orgName: [{ required: true, message: '请输入机构名称', trigger: 'blur' }],
                latitude: [{ required: true, message: '请输入纬度', trigger: 'blur' }],
                longitude: [{ required: true, message: '请输入经度', trigger: 'blur' }],
                orgLogo: [{ required: false, message: '请上传LOGO', trigger: 'blur' }],
                orgAddress: [{ required: true, message: '请输入机构详细地址', trigger: 'blur' }],
                remark: [{ required: false, message: '请输入备注', trigger: 'blur' }],
                orgProvince: [{ required: true, message: '请选择所在省/市/区', trigger: 'blur' }],
                orgCity: [{ required: false, message: '请选择所在城市', trigger: 'blur' }],
                orgCounty: [{ required: false, message: '请选择所在区/县', trigger: 'blur' }]
            }
        }
    },
    mounted() {
        this.loadOrgTree()
        this.initMap()
    },
    methods: {
        doPosition(value) {
            let la = value.location.split(',')
            this.map.setCenter(la) //设置地图中心点
            var marker = new AMap.Marker({
                position: la,
                // icon: './img/alarm1.png',
                map: this.map
            })
            this.submitForm.longitude = la[0]
            this.submitForm.latitude = la[1]
            this.submitForm.orgAddress = value.address
            this.submitForm.orgName = value.name
            this.submitForm.orgProvince = value.district
            //district
        },
        initMap() {
            this.map = new AMap.Map('container', {
                resizeEnable: true,
                rotateEnable: false,
                pitchEnable: false,
                zoom: 20,
                pitch: 65,
                rotation: 0,
                viewMode: '2D', //开启3D视图,默认为关闭
                zooms: [3, 20]
            })
            this.disabled = true
            this.submitForm = {
                orgName: '',
                sort: '',
                orgId: '',
                parentId: 0,
                latitude: '',
                longitude: '',
                orgLogo: '',
                orgAddress: '',
                remark: '',
                orgProvince: '',
                orgCity: '',
                orgCounty: '',
                delFlag: 0,
                codes: ''
            }
        },
        handleChange(value) {
            for (var k = 0, lengthk = provinceAndCity.length; k < lengthk; k++) {
                //确定省
                if (provinceAndCity[k].code == value[0]) {
                    this.submitForm.orgProvince = provinceAndCity[k].name
                    if (provinceAndCity[k].cityList && value.length >= 2 && value[1] != '') {
                        for (var i = 0, lengthi = provinceAndCity[k].cityList.length; i < lengthi; i++) {
                            //确定市
                            if (provinceAndCity[k].cityList[i].code == value[1] || provinceAndCity[k].cityList.length == 1) {
                                this.submitForm.orgCity = provinceAndCity[k].cityList[i].name
                                //确定区
                                if (provinceAndCity[k].cityList[i].areaList && value.length == 3 && value[2] != '') {
                                    for (var j = 0, lengthj = provinceAndCity[k].cityList[i].areaList.length; j < lengthj; j++) {
                                        if (provinceAndCity[k].cityList[i].areaList[j].code == value[2]) {
                                            this.submitForm.orgCounty = provinceAndCity[k].cityList[i].areaList[j].name
                                            break
                                        }
                                    }
                                }
                                break
                            }
                        }
                    }
                    break
                }
            }
        },
        renderContent(h, { node, data, store }) {
            return (
                <span class="custom-tree-node">
                    <span>{node.label}</span>
                    <span>
                        <el-button size="mini" type="text" on-click={() => this.editRow(data)}>
                            编辑
                        </el-button>
                        <el-button size="mini" type="text" on-click={() => this.removeRow(node, data)}>
                            删除
                        </el-button>
                    </span>
                </span>
            )
        },
        editRow(data) {
            this.showUpdateBtn = true
            this.disabled = false
            API.getObj(data.id).then(res => {
                //"110000", "110100", "110101"
                if (res.data.code === 0) {
                    if (res.data.data.codes) {
                        res.data.data.codes = res.data.data.codes.split(',')
                    }
                    this.submitForm = res.data.data
                }
            })
        },
        removeRow(data) {
            console.log(data)
            API2.getOwnerByOrgId(data.data.id).then(res=>{
                if(res.data.code === 0&&res.data.data.length>0){
                    this.$confirm('当前小区已经录入了用户数据，是否删除当前小区及其用户数据?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        API.delObj({id:data.data.id,flag:'deluser'}).then(res => {
                            if (res.data.code === 0) {
                                this.$message.success('删除成功')
                                this.loadOrgTree()
                                this.initMap()
                            }
                        })
                    })
                }else{
                    this.$confirm('删除后无法恢复,是否删除当前机构数据?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        API.delObj({id:data.data.id}).then(res => {
                            if (res.data.code === 0) {
                                this.$message.success('删除成功')
                                this.loadOrgTree()
                                this.initMap()
                            }
                        })
                    })
                }
            })
            
        },
        addOrg() {
            this.$refs['submitForm'].resetFields()
            this.submitForm.orgId = ''
            this.disabled = false
            this.showAddBtn = true
            this.showUpdateBtn = false
        },
        loadOrgTree() {
            API.fetchTree().then(res => {
                if (res.data.code === 0) {
                    this.treeData = res.data.data
                }
            })
        },
        uploadSuccess(response) {
            this.filePath = response.data
            if (response.data.indexOf('/static') > -1) {
                this.filePath = response.data.substr(response.data.indexOf('/static'))
            }
            this.submitForm.orgLogo = this.filePath
        },
        doSave() {
            this.$refs['submitForm'].validate(valid => {
                if (valid) {
                    let obj = JSON.parse(JSON.stringify(this.submitForm))
                    if(!!obj.codes) {
                        obj.codes = obj.codes.join(',')
                    }
                    API.addObj(obj).then(res => {
                        if (res.data.code === 0) {
                            this.$message.success('保存成功')
                            this.loadOrgTree()
                            this.initMap()
                        }
                    })
                }
            })
        },
        handleNodeClick(data) {}
    }
}
</script>

<style lang="scss" scoped>
.org {
    width: 100%;
    height: calc(100% - 100px);
    background-color: #fff;
}
</style>